<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>HTML5 History API</title>
    <link rel="stylesheet" href="./common.css">
</head>
<body>
    <!-- url 
    domain , 组织文件,  向用户提供很多资源
    链接把资源组织起来 
    一切皆资源  Restful  -->
    <div class="wrapper">
        <ul class="nav">
            <li><a href="index.html">Home</a></li>
            <li><a href="fluffy.html">Fluffy</a></li>
            <li><a href="socks.html">Socks</a></li>
            <li><a href="whiskers.html">Whiskers</a></li>
        </ul>
        <p class="content">Welcome to Kittens! Home of Fluffy, Socks, and Whiskers. If you're not suffering from a cute overdose within the hour, then you really are a heartless bugger! Now lets look at some cats!</p>
        <div class="media">
            <img src="http://www.ichong123.com/uploads/2014/08/m1.jpg" alt=""  class="photo">
        </div>
    </div>
    <script> 
    // 对传统web网站发起优化
    // 使用ajax 拉取数据 不用刷新整个页面 不用白一下
    function getHtml(href,callback){
        const xhr =new XMLHttpRequest();
        xhr.open("GET",href);
        xhr.send();//发送请求
        xhr.onreadystatechange=function(){
            if(xhr.readyState==4){//服务器响应 完全到达了
                callback(xhr.responseText);
            }
        }

    }

    function createState(data){
        const contentMatches=data.match(/content">(.+)</)
        const photoMatches=data.match(/img.+src="(.+?)"\s/)
        console.log(contentMatches[1]);
        console.log(photoMatches[1]);
        const content=contentMatches[1];
        const photo=photoMatches[1];
        return {
            content,
            photo

        }

    }
    window.addEventListener('DOMContentLoaded',function(){
        // html +css 页面渲染
        // 比 loaded 更早的 js运行 ，进行交互
        // console.log('loaded');
        const links =document.querySelectorAll('.nav li a');
        links.forEach(link=>{
            link.addEventListener('click',function(event){
                // 传统a 标签点完就白屏
                event.preventDefault();
                // let href=this.href;
                let href = event.target.href;
                // console.log(href);
                // const xhr =new XMLHttpRequest();
                getHtml(href,function(data){
                    // console.log(data);
                    // 正则的过程
                    let state=createState(data);
                    // console.log(state);
                    document.querySelector('.content').innerText=state.content;
                    document.querySelector('.photo').src=state.photo;
                })
            })
        })
    })    

    // // 生命周期 所有的资源都加载完成
    // window.onload=function(){

    // }
    
    </script>
</body>
</html>